import config from './config';
import auth from './auth';
import axios from 'axios';
import qs from 'qs';

axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

export default function api({url = '/', data = {}, method = 'post', notNeedLogin = false, notNeedTrans = false}, more = {}) {
    for (let i in data) {
        if (data.hasOwnProperty(i)) {
            let val = data[i];
            if (val === null || val === undefined) {
                data[i] = '';
            }
        }
    }

    return auth.getUserInfo()
        .then(userInfo => {
            data = {
                ...data,
                user_id: userInfo.id || 0
            };
        })
        .finally(() => {
            if (!notNeedLogin && !data.user_id) {
                auth.goLogin();
                return Promise.reject({
                    code: -999,
                    msg: '请先登录'
                });
            }
            let requestConfig = {
                ...{
                    baseURL: config.baseUrl,
                    url,
                    method,
                    data,
                    timeout: 120 * 1000
                }, ...more
            };
            return request(requestConfig, notNeedTrans);
        });
}

function request(requestConfig, notNeedTrans) {
    return new Promise((resolve, reject) => {
        if (requestConfig.method === 'get') {
            requestConfig.params = data;
        } else {
            if (!notNeedTrans) {
                requestConfig.transformRequest = data => qs.stringify(data);
            }
        }
        return axios(requestConfig).catch(e => {
            console.error(e);
            return Promise.reject({
                code: -9999,
                msg: '客户端捕获未知错误'
            });
        }).then(res => {
            res = res.data;
            if (res.errno === 0) {
                resolve(res.result);
            }
            reject({
                code: res.errno,
                msg: res.error
            });
        }).catch(e => {
            console.error(e);
            return reject({
                code: -9999,
                msg: '客户端捕获未知错误'
            });
        });
    });
}